from flask import session
from flask_restful import Resource, fields, marshal_with

from app.models import User, Collection, Author, Dynasty

poem_all = {
    "p_id": fields.Integer(attribute="p_id"),
    "p_name": fields.String(attribute="p_name"),
}

author_all = {
    "a_id": fields.Integer(attribute="a_id"),
    "a_name": fields.String(attribute="a_name"),
}

dynasty_all = {
    "d_id": fields.Integer(attribute="d_id"),
    "d_name": fields.String(attribute="d_name"),
}

collect_info = {
    'status': fields.Integer,
    'poems': fields.Nested(poem_all),
    'authors': fields.Nested(author_all),
    'dynastys': fields.Nested(dynasty_all),
}


class CollectResource(Resource):
    @marshal_with(collect_info)
    def get(self):
        if session['u_name']:
            name = session['u_name']
            user = User.query.filter(User.u_name == name)
            user = user.first()
            collects = Collection.query.get(user.u_id)
            poems = collects.poem.all()
            authors = [Author.query.filter(Author.a_id == i.p_author_id).first() for i in poems]
            dynastys = [Dynasty.query.filter(Dynasty.d_id == i.p_dynasty_id).first() for i in poems]
            return {'status': 200,
                    'poems': poems,
                    'authors': authors,
                    'dynastys': dynastys,
            }
        else:
            return {'status': 400, 'msg': 'please login'}

    def post(self):
        pass

    def put(self):
        pass

    def delete(self):
        pass
